package homework;

import java.util.*;

public class HomeTest03 {
    public static void main(String[] args) {
        //1.创建List集合，存储Student元素，并遍历
        List<Student> stu = new ArrayList<>();
        //添加元素
        Student s1 = new Student(1, "张三", 18, "男");
        Student s2 = new Student(2, "李四", 19, "女");
        Student s3 = new Student(3, "王五", 20, "男");
        Student s4 = new Student(4, "赵六", 21, "男");
        stu.add(s1);
        stu.add(s2);
        stu.add(s3);
        stu.add(s4);
        //遍历
        for (Student student : stu) {
            System.out.println(student);
        }

        //创建Map集合
        Map<Integer, Student> map = listToMap(stu);

        System.out.println("添加进Map后");
        //遍历
        for (Map.Entry<Integer, Student> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "--" + entry.getValue());
        }
        System.out.println("添加进List后");
        List<Student> newList = mapToList(map);
        //遍历
        for (Student student : newList) {
            System.out.println(student);
        }
    }

    //将List中Student元素封装到Map中
    public static Map<Integer, Student> listToMap(List<Student> stu) {
        Map<Integer, Student> map = new HashMap<>();
        for (Student student : stu) {
            map.put(student.getId(), student);
        }
        return map;
    }

    //将Map中元素封装到List中
    public static List<Student> mapToList(Map<Integer, Student> map) {
        return new ArrayList<>(map.values());//复制map的value值到List中
    }
}

class Student {
    private int id;
    private String name;
    private int age;
    private String sex;

    public Student(int id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public Student() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name) && Objects.equals(sex, student.sex);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, sex);
    }

    @Override
    public String toString() {
        return "学号：" + id + "姓名：" + name + "  年龄：" + age + "  性别：" + sex;
    }
}